import React from 'react';
import * as echarts from 'echarts';
import emitter from '#/utils/events';

export default class TRChart extends React.Component {
  constructor(props) {
    super(props);
    this.events = props?.events || [];
    this.chartIns = null;
    this._onHandleResize = this._onHandleResize.bind(this);
  }

  componentDidMount() {
    window.addEventListener('resize', this._onHandleResize);
    emitter.addListener('onChangeMnue', this._onHandleResize);
    this.chartIns.setOption(this.props?.config || {}, true);
    this.chartIns.resize();
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this._onHandleResize);
    emitter.removeListener('onChangeMnue', this._onHandleResize);
    this.chartIns.dispose();
    this.chartIns = null;
  }

  _onHandleResize() {
    setTimeout(() => {
      this.chartIns?.resize();
    }, 500);
  }

  _up(options = {}, opts = {}) {
    this.chartIns.setOption(options, opts);
    this.chartIns.resize();
  }

  render() {
    return (
      <div
        style={{ width: '100%', height: '100%' }}
        ref={(el) => el && !this.chartIns && (this.chartIns = echarts.init(el))}
      />
    );
  }
}
